<template>
  <div>
    <el-row class="lock-btn" style="margin-bottom:1%">
      <el-button-group>
        <el-button type="warning" :disabled="userState" size="primary" round @click="batchChangePrice">批量改价格</el-button>
        <el-button style="background:#3cbae6;border:1px solid #3cbae6" :disabled="userState" size="primary" type="primary" v-if="roleIndex == false" round @click="batchChangeType">批量改类型</el-button>
      </el-button-group>
      <el-button-group>
        <el-button :disabled="userState" size="primary" type="success" v-if="roleIndex == false" round @click="addLockDialog">添加</el-button>
        <el-button :disabled="userState" size="primary" type="danger"  v-if="roleIndex == false" round @click="batchDelete">删除</el-button>
      </el-button-group>

      <el-button-group style="width:500px">
      <el-input v-model="queryParams.lockMac" style="width:200px;float: left;margin-left: 1%;" clearable placeholder="请输入泊位名称">
      </el-input>

      <el-button :disabled="userState" style="margin-left: 0.6%;margin-top: 0.2%;" size="medium" type="primary" @click="loadLocksList" round>搜索</el-button>
    </el-button-group>

    </el-row>
    <el-row style="box-shadow: rgb(205 205 205) 1px 1px 8px;">
      <el-col :span="24">
        <el-table :header-cell-style="{ background: '#ecf3fd',color:'#000000' }" highlight-current-row  ref="lockTable" @cell-dblclick="handleCellDbclick" v-loading="loading" :data="lockList" :stripe="true" :row-key="'lockId'" :max-height="clientHeight" :height="clientHeight" @selection-change="handleTableChange">
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column prop="lockMac" label="逻辑编号" width="" sortable align="center"></el-table-column>
          <el-table-column prop="lockAddress" label="泊位名称" width="" align="center"></el-table-column>
          <el-table-column prop="lockType" label="泊控器类型" width="" align="center"></el-table-column>
          <el-table-column prop="lockPrice" label="支付金额(元)" width="" align="center"></el-table-column>
          <el-table-column label="二维码" width="" align="center">
            <template slot-scope="scope">
              <el-popover trigger="click" placement="top" @show="handleQrCode(scope.row.lockMac)" :popper-class="`tooltip${scope.row.lockMac}`">
                <div style="width:150px;height:150px;" :ref="`qrCodeDiv${scope.row.lockMac}`"></div>
                <div slot="reference" class="qr-wrapper">
                  <el-tag size="medium">{{ scope.row.lockMac }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="工作状态" width="100" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.lockStatus === '空闲中'" :disabled="userState" size="mini" type="danger" @click="updateStatus(scope.row)">停止</el-button>
              <el-button v-if="scope.row.lockStatus === '使用中'" :disabled="userState" size="mini" type="danger" @click="updateStatus(scope.row)">停止</el-button>
              <el-button v-if="scope.row.lockStatus === '预约中'" :disabled="userState" size="mini" type="danger" @click="updateStatus(scope.row)">停止</el-button>
              <el-button v-if="scope.row.lockStatus === '调试中'" :disabled="userState" size="mini" type="primary" @click="updateStatus(scope.row)">离线/启动</el-button>
              <el-button v-if="scope.row.lockStatus === '人工停止中'" :disabled="userState" size="mini" type="primary" @click="updateStatus(scope.row)">人工停止/启动</el-button>

              
            </template>
          </el-table-column>
          <el-table-column v-if="roleIndex == false" prop="battery" label="充电桩" align="center">
            <template slot-scope="scope">
              <el-button  v-if="scope.row.battery !== null" :disabled="userState" type="info" size="mini" effect="dark" @click="handleBinding(scope.row)">已绑定</el-button>
              <el-button  v-else-if="scope.row.battery === null" :disabled="userState" type="primary" size="mini" @click="handleBinding(scope.row)">未绑定</el-button>
            </template>
          </el-table-column>
          <el-table-column label="泊控器状态" width="100px" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.lockStatus === '使用中'" size="medium" type="danger">使用中</el-tag>
              <el-tag v-else-if="scope.row.lockStatus === '空闲中'" size="medium" type="success">空闲中</el-tag>
              <el-tag v-else-if="scope.row.lockStatus === '预约中'" size="medium" type="info">预约中</el-tag>
              <el-tag v-else-if="scope.row.lockStatus === '调试中'" size="medium" type="warning">调试中</el-tag>
              <el-tag v-else-if="scope.row.lockStatus === '人工停止中'" size="medium" type="warning">人工停止中</el-tag>
              <el-tag v-else size="medium">未知状态</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createDate" label="创建时间" width="180" align="center" sortable></el-table-column>
          <el-table-column prop="remark" label="备注" align="center"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination layout="total,sizes,prev, pager,next,jumper" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 30, 40, 100]" @size-change="handlePageChange" @current-change="handleNoChange"></el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="批量修改类型" :visible.sync="changeTypeDialog" :width="'422px'">
      <el-form :model="formType" :rules="typeRules" ref="formType">
        <el-form-item :label="dialogLable" :label-width="labelWidth" prop="selected">
          <el-select v-model="formType.selected" clearable :placeholder="dialogPlaceholder">
            <el-option v-for="(value, key) in typeAstatus" v-bind:key="key" :label="value" :value="key"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeTypeDialog = false">取 消</el-button>
        <el-button type="primary" @click="batchBtn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加泊位" :visible.sync="addDialog" :width="'422px'">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="物理编号" :label-width="labelWidth" prop="ip">
          <el-input v-model="form.ip" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="逻辑编号" :label-width="labelWidth" prop="mac">
          <el-input v-model="form.mac" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="泊位名称" :label-width="labelWidth" prop="address">
          <el-input v-model="form.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" :label-width="labelWidth" prop="price">
          <el-input v-model="form.price" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型" :label-width="labelWidth" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="(value, key) in this.$store.state.parklock.type" v-bind:key="key" :label="value" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="控制方式" :label-width="labelWidth" prop="lockType">
          <el-input v-model="form.lockType" value="1" placeholder="地锁" disabled></el-input>
          <!-- <el-select  v-model="form.lockType" placeholder="请选择方式">
            <el-option key="1" label="地锁" :value="1"></el-option>
            <el-option key="2" label="道闸" :value="2"></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="所属停车场" :label-width="labelWidth" prop="parkfieldId">
          <el-select v-model="form.parkfieldId" @change="parkfieldChange" placeholder="请选择所属停车场">
            <el-option v-for="parkfield in parkfields" v-bind:key="parkfield.id" :label="parkfield.name" :value="parkfield.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域" :label-width="labelWidth" prop="position">
          <el-select v-model="form.position" placeholder="请选择所属区域">
            <el-option v-for="area in areas" v-bind:key="area.id" :label="area.name" :value="area.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="labelWidth">
          <el-input v-model="form.remark" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addLock">确 定</el-button>
      </div>
    </el-dialog>
 
    <el-dialog title="绑定充电桩" :visible.sync="bindDialog" :width="'422px'">
      <el-form :model="bindForm" :rules="bindRules" ref="bindForm">
        <el-form-item label="充电桩" :label-width="labelWidth" prop="battery">
          <el-select v-model="bindForm.battery" placeholder="请选择充电桩">
            <el-option v-for="charger in chargers" v-bind:key="charger.id" :label="charger.mac+'【'+charger.address+'】'" :value="charger.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindDialog = false">取 消</el-button>
        <el-button @click="unbindCharger">解 除</el-button>
        <el-button type="primary" @click="bindCharger">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import {
  batchChange,
  rm,
  addLockApi,
  getNobindCharger,
  bindChargerApi,
  loadLocksApi,
  loadLocksListApi
} from "../../api/parkLock.js";
import { loadParkfieldApi } from "../../api/parkfield.js";
import { loadAreaApi } from "../../api/area.js";
import { getNickName, getTestUserName,getRoleId } from "../../util/auth";
export default {
  name: "runInfo",
  data: function () {
    return {
      config: window.$config,
      clientHeight:
        Math.max(
          document.documentElement.scrollHeight,
          document.body.scrollHeight
        ) -
        132 -
        5 +
        10 -
        28,
      lockList: [],
      loading: false,
      pageNo: 1,
      pageSize: 20,
      total: 0,
      multipleSelection: [],
      changeTypeDialog: false,
      addDialog: false,
      numberDialog: false,
      userDialog: false,
      labelWidth: "110px",
      selected: "",
      typeAstatus: {},
      dialogLable: "",
      dialogPlaceholder: "",
      parkfields: [],
      areas: [],
      form: {
        price:24
      },
      queryParams:{
        lockMac:""
      },
      numberForm: {},
      userForm: {},
      lunxun: {},
      bindDialog: false,
      bindForm: {},
      chargers: [],
      roleIndex: true,

      rules: {
        ip: [
            { required: true, message: '请输入物理编号', trigger: 'blur' }
          ],
        mac: [
            { required: true, message: '请输入逻辑编号', trigger: 'blur' }
          ],
        address: [
            { required: true, message: '请输入区域地址', trigger: 'blur' }
          ],
        price: [
            { required: true, message: '请输入价格', trigger: 'blur' }
          ],
        type: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
        // lockType: [
        //     { required: true, message: '请选择控制方式', trigger: 'change' }
        //   ],
        parkfieldId: [
            { required: true, message: '请选择所属停车场', trigger: 'change' }
          ],
        position: [
            { required: true, message: '请选择所属区域', trigger: 'change' }
          ],
      },

      formType:{},

      typeRules: {
        selected: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
      },

      bindRules: {
        battery: [
            { required: true, message: '请选择充电桩', trigger: 'change' }
          ],
      },

    };

  },
  methods: {
 
    handleCellDbclick (row, column, cell, event) {
      if (userState) {
        return
      }
  
      const self = this;
      if (column.property === "userName") {
        self.userForm = {
          id: row.lockId,
          userId: row.userId
        };
        self.userDialog = true;
      }  
    },
    handleBinding (row) {
      const self = this;
      let areaId = row.areaId;
      getNobindCharger(areaId).then(resp => {
        self.chargers = resp.data;
        self.bindForm = {
          id: row.lockId,
          battery: row.battery
        };
        self.$nextTick(()=>{
        if(self.$refs.bindForm != undefined){
          self.$refs.bindForm.resetFields();
        }
      })
        self.bindDialog = true;
      });
    },
    bindCharger () {
      const self = this;
      self.$refs.bindForm.validate((valid) => {
        if (valid) {
          bindChargerApi(self.bindForm.id, self.bindForm.battery).then(resp => {
            if (resp.errmsg === "ok" && resp.data === 1) {
              self.bindDialog = false;
              self.loadLocks(self.pageNo, self.pageSize);
              self.$notify({
                title: "成功",
                message: "充电桩绑定成功",
                type: "success"
              });
            }
          });
        }
      });
    },
    unbindCharger () {
      const self = this;
      bindChargerApi(self.bindForm.id, 0).then(resp => {
        if (resp.errmsg === "ok" && resp.data === 1) {
          self.bindDialog = false;
          self.loadLocks(self.pageNo, self.pageSize);
          self.$notify({
            title: "成功",
            message: "解除绑定成功",
            type: "success"
          });
        }
      });
    },
    addLock () {
      let _this = this;
      _this.$refs.form.validate((valid) => {
          if (valid) {
            addLockApi(_this.form).then(resp => {
              if (resp.errmsg === "ok" && resp.data === 1) {
                _this.addDialog = false;
                _this.loadLocks(_this.pageNo, _this.pageSize);
                _this.$notify({
                  title: "成功",
                  message: "泊控器添加成功",
                  type: "success"
                });
              }
            });
          }
      });
    },
    addLockDialog () {
      let _this = this;
      _this.$nextTick(()=>{
        if(_this.$refs.form != undefined){
          _this.$refs.form.resetFields();
        }
      })
      this.addDialog = true;
      loadParkfieldApi().then(resp => {
        _this.parkfields = resp.data.dataList;
      });
    },
    parkfieldChange (value) {
      let _this = this;
      loadAreaApi({ positionId: value }).then(resp => {
        _this.areas = resp.data.dataList;
      });
    },
    batchDelete () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }
      let _this = this;
      this.$confirm('确认批量删除泊控器', '提示', {
        type: 'warning'
      })
        .then(_ => {
          rm(this.multipleSelection).then(function (resp) {
            if (resp.errmsg === "ok") {
              for (let i = 0; i < _this.multipleSelection.length; i++) {
                for (let j = 0; j < _this.lockList.length; j++) {
                  if (
                    _this.multipleSelection[i].lockId == _this.lockList[j].lockId
                  ) {
                    break;
                  }
                }
              }
              _this.multipleSelection = []
              _this.$refs.lockTable.clearSelection();
              _this.$notify({
                title: "成功",
                message: "泊控器删除成功",
                type: "success"
              });
            }
          });
        })
    },
    batchBtn () {
      let _this = this;
      _this.$refs.formType.validate((valid) => {
        if (valid) {
          if (_this.formType.selected == null || _this.formType.selected == "") {
            return;
          }
          if (_this.dialogLable == "状态") {
            batchChange(_this.multipleSelection, _this.formType.selected, null, null)
              .then(function (resp) {
                if (resp.errmsg === "ok") {
                  _this.multipleSelection = []
                  _this.$refs.lockTable.clearSelection();
                  _this.loadLocks(_this.pageNo, _this.pageSize);
                  _this.$notify({
                    title: "成功",
                    message: "状态修改成功",
                    type: "success"
                  });
                } else {
                  _this.$notify({
                    title: "失败",
                    message: "状态修改失败，请稍后重试。",
                    type: "error"
                  });
                }
              })
              .finally(function () {
                _this.changeTypeDialog = false;
              });
          } else {
            batchChange(_this.multipleSelection, null, _this.formType.selected, null)
              .then(function (resp) {
                if (resp.errmsg === "ok") {
                  _this.multipleSelection = []
                  _this.$refs.lockTable.clearSelection();
                  _this.loadLocks(_this.pageNo, _this.pageSize);
                  _this.$notify({
                    title: "成功",
                    message: "类型修改成功",
                    type: "success"
                  });
                } else {
                  _this.$notify({
                    title: "失败",
                    message: "类型修改失败，请稍后重试。",
                    type: "error"
                  });
                }
              })
              .finally(function () {
                _this.changeTypeDialog = false;
              });
          }
        }
      });
    },
    batchChangeStatus () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }
      this.selected = "";
      this.dialogLable = "状态";
      this.dialogPlaceholder = "请选择状态";
      this.typeAstatus = this.$store.state.parklock.status;
      this.changeTypeDialog = true;
    },
    batchChangeType () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }
      this.$nextTick(()=>{
        if(this.$refs.formType != undefined){
          this.$refs.formType.resetFields();
        }
      })
      this.selected = "";
      this.dialogLable = "类型";
      this.dialogPlaceholder = "请选择类型";
      this.typeAstatus = this.$store.state.parklock.type;
      this.changeTypeDialog = true;
    },
    batchChangePrice () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择泊控器",
          type: "warning"
        });
        return;
      }
      this.$prompt("请输入价格", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
        inputErrorMessage: "请输入正确价格"
      }).then(({ value }) => {
        let _this = this;
        batchChange(this.multipleSelection, null, null, value).then(function (
          resp
        ) {
          _this.multipleSelection = []
          _this.$refs.lockTable.clearSelection();
          if (resp.errmsg === "ok") {
            for (let i = 0; i < _this.multipleSelection.length; i++) {
              _this.multipleSelection[i].lockPrice = value;
            }
            _this.$notify({
              title: "成功",
              message: "价格修改成功",
              type: "success"
            });
          } else {
            _this.$notify({
              title: "失败",
              message: "价格修改失败，请稍后重试。",
              type: "error"
            });
          }
        });
      });
    },
    handlePageChange (pageSize) {
      this.pageSize = pageSize;
      this.loadLocks(this.pageNo, this.pageSize);
    },
    handleNoChange (pageNo) {
      this.pageNo = pageNo;
      this.loadLocks(this.pageNo, this.pageSize);
    },
    handleTableChange (val) {
      this.multipleSelection = val;
    },

    loadLocksList() {
      let _this = this;
      _this.loading = true;
      loadLocksListApi({ address:_this.queryParams.lockMac}).then(resp => {
        _this.loading = false;
      
            _this.lockList = resp.data;
 
      });

      _this.loading = false;

    },


    loadLocks (pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
     
        loadLocksApi({pageNo:pageNo, pageSize:pageSize,name:_this.queryParams.lockMac}).then(function (resp) {
          _this.loading = false;
          if (resp.errmsg === "ok") {
            _this.total = resp.data.totalNum;
            _this.lockList = resp.data.dataList;
            for (let i = 0; i < _this.lockList.length; i++) {
              if(_this.lockList[i].battery === undefined){
                _this.lockList[i].battery = null;
              };
            }
          }
        })
        .catch(function (e) {
          console.log(e);
        });
    },

    queryBtn () {
      let _this = this
      _this.loading = true
     
      _this.loadLocks(_this.pageNo, _this.pageSize, _this.queryParams)
      
    },

    handleQrCode (lockMac) {
 
      document.getElementsByClassName(`tooltip${lockMac}`)[1].children[0].innerHTML = "";
      var qrcode = new QRCode(document.getElementsByClassName(`tooltip${lockMac}`)[1].children[0], {
        text: `${this.config.server}/unlock/${lockMac}`,
        width: 150, //图像宽度
        height: 150, //图像高度
        colorDark: "#000000", //前景色
        colorLight: "#ffffff", //背景色
        typeNumber: 4,
        correctLevel: QRCode.CorrectLevel.H
      });
    },
    
    updateStatus(row) {
      let _this = this;
      _this.multipleSelection[0] = row;
 
      let status = row.lockStatus == '调试中' ||  row.lockStatus == '人工停止中'?2:99;

      console.log(_this.queryParams);
         
      batchChange(_this.multipleSelection, status, null, null)
          .then(function (resp) {
            if (resp.errmsg === "ok") {
              //  _this.loadLocks(_this.pageNo, _this.pageSize,_this.queryParams);
              _this.loadLocksList();
              
              _this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success"
              });
            } else {
              _this.$notify({
                title: "失败",
                message: "操作失败，请稍后重试。",
                type: "error"
              });
            }
          })
    }
  },
  computed: {
    userState () {
      return getNickName() === getTestUserName();
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      let _this = this;
      _this.loadLocks(_this.pageNo, _this.pageSize);
      _this.lunxun = setInterval(function () {
        _this.loadLocks(_this.pageNo, _this.pageSize);
      }, 60000);
      this.roleIndex = getRoleId()==1?false:true;
      this.$store.dispatch("loadStatus");
      this.$store.dispatch("loadType");
    });
  },
  beforeDestroy: function () {
    clearInterval(this.lunxun);
  }
};
</script>

<style scoped>


.page-tool div {
  text-align: right;
}

.lock-btn {
  margin-bottom: 5px;
  margin-top: -10px;
}
 
.qrcode-frame .qrcode_plugins_box {
  margin-top: -220px;
}
</style>
